#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<string>
#include<list>
#include<algorithm>
using namespace std;


void test_string8()
{
	string s1("hello world");
	cout << s1 << endl;

	s1.assign("111111");
	cout << s1 << endl;

	// 慎用，因为效率不高 -> O(N)
	// 实践中需求也不高
	string s2("hello world");
	s2.insert(0, "xxxx");
	cout << s2 << endl;

    s2 = 'y' + s2;

	char ch = 'y';
	cin >> ch;
	s2.insert(0, 1, ch);
	cout << s2 << endl;

	s2.insert(s2.begin(), 'y');
	cout << s2 << endl;

	s2.insert(s2.begin(), s1.begin(), s1.end());
	cout << s2 << endl;
}

void test_string9()
{
	string s1("hello world");
	cout << s1 << endl;

	// erase效率不高，慎用，和insert类似,要挪动数据
	s1.erase(0, 1);
	cout << s1 << endl;

	//s1.erase(5);
	s1.erase(5, 100);
	cout << s1 << endl;

	// replace效率不高，慎用，和insert类似,要挪动数据
	string s2("hello world");
	s2.replace(5, 1, "%20");
	cout << s2 << endl;

	string s3("hello world hello bit");
	for (size_t i = 0; i < s3.size(); )
	{
		if (s3[i] == ' ')
		{
			s3.replace(i, 1, "%20");
			i += 3;
		}
		else
		{
			i++;
		}
	}
	cout << s3 << endl;

	string s4("hello world hello bit");
	string s5;
	for (auto ch : s4)
	{
		if (ch != ' ')
		{
			s5 += ch;
		}
		else
		{
			s5 += "%20";
		}
	}
	cout << s5 << endl;
}

void TestPushBack()
{
	string s;
	// 知道需要多少空间，提前开好
	s.reserve(200);
	s[100] = 'x';

	size_t sz = s.capacity();
	cout << "capacity changed: " << sz << '\n';

	cout << "making s grow:\n";
	for (int i = 0; i < 200; ++i)
	{
		s.push_back('c');
		if (sz != s.capacity())
		{
			sz = s.capacity();
			cout << "capacity changed: " << sz << '\n';
		}
	}
}

void test_string10()
{
	string s1("hello world hello bit");
	string s1;
	cout << s1.size() << endl;
	cout << s1.capacity() << endl;
	cout << s1.max_size() << endl;
	for (size_t i = 0; i < s1.max_size(); i++)
	{
		s1 += 'x';
	}

	cout << s1.size() << endl;

	TestPushBack();

	string s1("111111111");
	string s2("11111111111111111111111111111111111111111111111111");

	cout << s1.capacity() << endl;

	// reserve 保留
	// reverse 逆置 反转
	s1.reserve(100);
	cout << s1.capacity() << endl;

	s1.reserve(20);
	cout << s1.capacity() << endl;
}

void test_string11()
{
	string s1;
	//s1.resize(5, '0');
	s1.resize(5);
	s1[4] = '3';
	s1[3] = '4';
	s1[2] = '5';
	s1[1] = '6';
	s1[0] = '7';
	// 76543

	// 插入(空间不够会扩容)
	string s2("hello world");
	s2.resize(20, 'x');

	// 删除
	s2.resize(5);

	try
	{
		//s2[10];
		//s2.at(10);
	}
	catch (const exception& e)
	{
		cout << e.what() << endl;
	}

	string file("test.cpp");
	FILE* fout = fopen(file.c_str(), "r");
	char ch = fgetc(fout);
	while (ch != EOF)
	{
		cout << ch;
		ch = fgetc(fout);
	}
}

void test_string12()
{
	string file("string.cpp.zip");
	size_t pos = file.rfind('.');
	//string suffix = file.substr(pos, file.size() - pos);
	string suffix = file.substr(pos);

	cout << suffix << endl;
}

// clang
int main()
{
	test_string12();

	/*std::cout << typeid(std::string::iterator).name() << std::endl;
	string s2("hello world");
	cout << sizeof(s2) << endl;*/

	return 0;
}